<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\TaskLogModel;

class TaskLogDao extends BaseDao
{
    public static function builder_query($params = []){
        $query = TaskLogModel::query();

        $query->when(checkIsHasField($params,'task_id'),function ($query)use ($params){
            $query->where('task_id',$params['task_id']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'order_id'),function ($query)use ($params){
            $query->where('order_id',$params['order_id']);
        });
        $query->when(checkIsHasField($params,'time'),function ($query)use ($params){
            $query->where('time',$params['time']);
        });

        return $query;
    }


    /**
     * @throws SysExceptions
     */
    public static function add($params = []){
        checkForData(['task_id','user_id','order_id'],['请选择任务','用户不正确','请选择订单'],$params);
        $params['time'] = date('Y-m-d');
        if(self::builder_query([
            'task_id'=>$params['task_id'],
            'order_id'=>$params['order_id'],
            'user_id'=>$params['user_id'],
            'time'=>$params['time']
        ])->exists()){
            self::error('任务今天已经提交过了!');
        }
        //查询任务信息
        $info = TaskDao::builder_query([
            'task_id'=>$params['task_id']
        ])->first()->toArray();

        if($info['task_day_nums'] <= self::builder_query([
                'task_id'=>$params['task_id'],
                'order_id'=>$params['order_id'],
                'user_id'=>$params['user_id'],
            ])->count()){
            self::error('任务已完成!');
        }
        if (self::builder_query()->create($params) === false){
            self::error('日志创建失败');
        }
    }

    public static function pages(array $all)
    {
        return self::builder_query($all)->paginate();
    }

    public static function all(array $params)
    {
        return self::builder_query($params)->get();
    }
}
